// cmd/protoc-gen-custom/main.go
package main

import (
	_ "embed"
	"fmt"
	"os"

	"google.golang.org/protobuf/compiler/protogen"
	"google.golang.org/protobuf/types/pluginpb"
)

const version = "1.0.0"

//go:embed bff.tmpl
var tmpl string

func main() {
	if len(os.Args) == 2 && os.Args[1] == "--version" {
		_, _ = fmt.Fprintf(os.Stdout, "protoc-gen-custom %v\n", version)
		return
	}

	opt := &protogen.Options{}
	opt.Run(func(gen *protogen.Plugin) error {
		gen.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
		for _, f := range gen.Files {
			if !f.Generate {
				continue
			}
			generateFile(gen, f)
		}
		return nil
	})
}

func generateFile(gen *protogen.Plugin, file *protogen.File) {
	if len(file.Services) == 0 {
		return
	}

	filename := file.GeneratedFilenamePrefix + ".bff.go"
	g := gen.NewGeneratedFile(filename, file.GoImportPath)

	g.P("// Code generated by protoc-gen-bff. DO NOT EDIT.")
	g.P("// Version: ", version)
	g.P()
	g.P("package ", file.GoPackageName)
	g.P()

	// 生成服务代码
	for _, service := range file.Services {
		_, _ = g.Write(render(parseService(g, service)))
	}
}
